package com.pingan.haofang.searchcloud.common.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import com.pingan.haofang.searchcloud.common.utils.RequestTraceUtil;

/**
 * 上下文Filter
 *
 * @author ZHANGBI617
 * @date 2017/3/10
 * @since 1.0.0
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ContextFilter extends OncePerRequestFilter {

    /**
     * 请求响应头的服务器信息key
     */
    public static final String HTTP_RESPONSE_SERVER = "X-ServerInfo";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {

            RequestTraceUtil.requestTraceStart();

            String serverInfo = String.format("%s(%s)",
                    InetAddressHelper.getServerHostName(), InetAddressHelper.getServerIp());
            response.addHeader(HTTP_RESPONSE_SERVER, serverInfo);

            filterChain.doFilter(request, response);
        } finally {
            RequestTraceUtil.requestTraceEnd();
        }
    }
}
